import React from 'react'
import {useState,useEffect} from 'react';
import { useHistory } from 'react-router';
import './Painting.css';
import img1 from './img/operation.png';

const Qa = () => {
    const [data,setData] = useState([]);
    const [num,setNum] = useState(1);
    const history = useHistory()
    useEffect(() => {
        fetch("https://api.52h5.xyz:3001/adminqa")
        .then(res=>res.json())
        .then(res=>{
            setData(res.data);
        })
        .catch(err=>{
            console.log(err)
        })
    }, [])
    // console.log(data);
    const pre = ()=>{
        if(num>1){
            setNum(num-1)
        }
    }
    const next = ()=>{
        if(num<data.length/10)
            setNum(num+1);
    }
    const addPainting  = ()=>{
        history.push('/index/addqa')
    }
    const delQa = (pid,qid)=>{
        fetch(`https://api.52h5.xyz:3001/adminqa/?pId=${pid}&&qId=${qid}`,{
            method:'delete',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        })
        .then(res=>res.text())
        .then(res=>{
            var newArr = data.filter(({pId,qId},index)=>pId!=pid&& qId!=qid);
            setData(newArr);
        })          
        .catch(err=>{
            console.log(err);
        })
    }
    return (
        <div className="board">
            <div className="info">
                <h3>题目列表</h3>
                <div id = "find">
                    <div className="add">
                        <img src={img1} alt=''></img>
                        <button onClick={()=>addPainting()}>添加题目信息</button>
                    </div>
                </div>
                <table className="painting">
                    <tbody>
                    <tr>
                        <th>序号</th>
                        <th>画作id</th>
                        <th>题目id</th>
                        <th>操作</th>
                    </tr>
                {
                    data.map(({pId,qId},index)=>{
                        if(index<num*10 && index>=(num-1)*10){
                        return(
                        <tr>
                            <td>{index+1}</td>
                            <td>{pId}</td>
                            <td>{qId}</td>
                            <td><button onClick={()=>history.push('/index/udqa'+qId)}>修改</button><button onClick={()=>delQa(pId,qId)}>删除</button></td>
                        </tr>
                        )
                        }
                    }
                    )
                }
                </tbody>                    
                </table>
                <div className="next">
                    <p>每页显示10条</p>
                    <button>第{num}页</button>
                    <button onClick={pre}>上一页</button>
                    <button onClick={next}>下一页</button>
                </div>
            </div>
        </div>
    )
}

export default Qa